﻿using System;
using System.Web.Mvc;
using System.Web.Routing;
using Web7.Core.InversionOfControl;
using Web7.Ioc;


//using Web7.Ioc;

namespace Web7.Core.ControllerFactories
{
    /// <summary>
    /// 主要作用:为Controller重新设置ActionInvoker
    /// </summary>
    public class DependencyInjectorControllerFactory : DefaultControllerFactory
    {
        private readonly IDependencyInjector _dependencyInjector;

        public DependencyInjectorControllerFactory(IDependencyInjector dependencyInjector)
        {
            this._dependencyInjector = dependencyInjector;
        }

        /// <summary>
        /// 获取Controller实例
        /// </summary>
        /// <param name="requestContext">Http请求上下文</param>
        /// <param name="controllerType">Controller类型</param>
        /// <returns></returns>
        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            IController iController = _dependencyInjector.GetService(controllerType) as IController;

            if (typeof(Controller).IsAssignableFrom(controllerType))
            {
                Controller controller = iController as Controller;

                //设置ActionInvoker
                if (controller != null)
                    controller.ActionInvoker = _dependencyInjector.GetService<IActionInvoker>();

                return iController;
            }

            return iController;
        }
    }
}
